package fr.utbm.set.safeplatoon.common.merging.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import fr.utbm.set.safeplatoon.common.merging.data.Evaluation;

public class ServerCMD implements Runnable{




	protected ServerSocket    socketEcoute;
	protected Socket          socketService;
	protected InputStream     entreeSocket;
	protected OutputStream    sortieSocket;

	private Evaluation evaluation;

	public ServerCMD(int pPort,Evaluation evaluation) throws IOException{
		
		this.evaluation = evaluation;
		this.socketEcoute = new ServerSocket(pPort);
		System.out.println("Connexion sur "+this.socketEcoute);
		while (this.socketService==null) {

			this.socketService = this.socketEcoute.accept();
		}
		this.sortieSocket = this.socketService.getOutputStream();
		this.entreeSocket = this.socketService.getInputStream();

	}

	public void sendDataByNetwork(String trame){

		try {
			System.out.println(trame);
			//ByteBuffer bbuf = ByteBuffer.allocate(trame.length());
			//bbuf.order(ByteOrder.nativeOrder()) ;
		
			this.sortieSocket.write(trame.getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void run() {
		while(true){
			// TODO Auto-generated method stub
			try {
				System.out.println("available :"+this.entreeSocket.available());
				if(this.entreeSocket.available()>25){

					byte[] test = new byte[3];

					this.entreeSocket.read(test);
					String strtest = new String(test);

					if(strtest.equals("CMD")){


						byte[] b = new byte[23];
						char[] c = new char[23];
						this.entreeSocket.read(b);
						String str = new String(b);
						str.replaceAll("[\r\n]+", "");
						//System.out.println(str);
						String [] trame = str.split(",");

						System.out.println("speed1 "+trame[2]);
						System.out.println("angle1 "+trame[1]);
						System.out.println("speed2 "+trame[4]);
						System.out.println("angle2 "+trame[3]);
						
						int s1 = Integer.parseInt(trame[2]);
						int s2 = Integer.parseInt(trame[4]);
						
						int a1 = Integer.parseInt(trame[1]);
						int a2 = Integer.parseInt(trame[3]);
						
						System.out.println("A"+evaluation.getCurrentOrder().x+"S"+evaluation.getCurrentOrder().y);
						String rep = "A"+(int)evaluation.getCurrentOrder().x+"S"+(int)evaluation.getCurrentOrder().y+",";
						for(int i=rep.length();i<15;i++)
							rep+="0";
						sendDataByNetwork(rep);

					}
					else
					{
						System.err.println("datalost");

					}

				}
				Thread.sleep(100);
			} catch (IOException | InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}




}
